package com.thiagov.poc;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class TourActivity extends Activity{

    private ImageAdapter mAdapter;
    private Context mContext;

    private ImageView foto;
    private int placeId = -1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tour);

        /* Habilita efeito de 'blur' na activity sobreposta. */
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

        Gallery g = (Gallery) findViewById(R.id.gal);
        mAdapter = new ImageAdapter(this);
        g.setAdapter(mAdapter);
        mContext = this;

        /* Listener chamado sempre que a imagem selecionada na galeria
         * eh alterada. */
        g.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View v,
                    int position, long id) {

                /* Altera a imagem mostrada. */
                selectImage(position);

                if (GameMapActivity.getPlayerLocation() == null) {
                    ((Button) findViewById(R.id.checkin)).setEnabled(false);
                    return;
                }

                /* Encontra, no banco de dados, a latitude e longitude do
                 * local mostrado. */
                Cursor cursor = DroidTour.dh.getDatabase().query("places", new String[] {"lat", "lng"}, 
                       "id=\"" + (position+1) + "\"", null, null, null, null);
                cursor.moveToFirst();

                /* Encontra a distancia entre o local e a posicao atual
                 * do jogador. */
                double latDif = cursor.getInt(0) - GameMapActivity.getPlayerLocation().getLatitudeE6();
                double longDif = cursor.getInt(1) - GameMapActivity.getPlayerLocation().getLongitudeE6();
                double distance = Math.sqrt(latDif*latDif + longDif*longDif);

                /* Habilita ou desabilita o botao de chek-in. */
                if (distance <= Definitions.thresholdDistance) {
                    ((Button) findViewById(R.id.checkin)).setEnabled(true);
                } else {
                    ((Button) findViewById(R.id.checkin)).setEnabled(false);
                }

                /* Armazena o id do local mostrado, para facilitar o check-in
                 * no banco de dados. */
                placeId = position+1;

                cursor.close();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {}
        });

        /* Imagem inicial a ser utilizada. */
        foto = (ImageView) findViewById(R.id.imageView1);
        foto.setImageResource(R.raw.pracaraulsoares);

        /* Acao do botao de voltar. */
        ((Button)findViewById(R.id.back)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        /* Acao do botao de chek-in. */
        ((Button)findViewById(R.id.checkin)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if (placeId != -1) {
                    ContentValues value = new ContentValues();
                    value.put("tourVisited", "True");
                    DroidTour.dh.getDatabase().update("places", value, "id=\""+ placeId + "\"", null);
    
                    CharSequence text = "Check-in realizado com sucesso!";
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(mContext, text, duration);
                    toast.show();
                } else {
                    CharSequence text = "Ops, something went wrog. =(";
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(mContext, text, duration);
                    toast.show();
                }
            }
        });
    }

    /* Escolhe a imagem a ser exibida com base na posicao da galeria. */
    private void selectImage(int position) {
        foto.setImageResource(mAdapter.getImageResource(position));
    }

    /**
     * Adapter utilizado pela galeria que exibe os locais.
     * @author thiagov
     *
     */
    public class ImageAdapter extends BaseAdapter {
        
        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return mImageIds.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);

            i.setImageResource(mImageIds[position]);
            i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setLayoutParams(new Gallery.LayoutParams(136, 88));
            
            //Coloca um background diferente no item
            //i.setBackgroundResource(R.raw.ufmg);

            /* Pesquisa o campo 'tourVisited' no banco de dados. */
            Cursor cursor = DroidTour.dh.getDatabase().query("places", new String[] {"tourVisited"}, 
                    "id=\"" + (position+1) + "\"", null, null, null, null);
            /* Seta a cor de background com base no resultado da query. */
            if (cursor.moveToFirst()) {
                if (cursor.getString(0).equals("True")) {
                    i.setBackgroundColor(Color.RED);
                    i.setPadding(5, 5, 5, 5);
                } else {
                    i.setBackgroundColor(Color.BLUE);
                    i.setPadding(5, 5, 5, 5);
                }
            }
            else {
                Log.d("MyActivity", "Something went wrong! =(");
            }

            cursor.close();

            return i;
        }

        private Context mContext;

        /* Cuidado! A ordem eh importante! */
        private Integer[] mImageIds = {
                R.raw.pracaraulsoares,
                R.raw.minhacasa,
                R.raw.ufmg,
                R.raw.pracaliberdade,
                R.raw.palaciodasartes,
                R.raw.parquemangabeiras
        };
        
        public int getImageResource(int index) {
            return mImageIds[index];
        }
    }

}
